package com.yunfatong.ojd.quarz.project.monitor.job.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.yunfatong.ojd.quarz.common.utils.poi.ExcelUtil;
import com.yunfatong.ojd.quarz.project.monitor.job.base.AjaxResult;
import com.yunfatong.ojd.quarz.project.monitor.job.base.BaseController;
import com.yunfatong.ojd.quarz.project.monitor.job.domain.Job;
import com.yunfatong.ojd.quarz.project.monitor.job.page.TableDataInfo;
import com.yunfatong.ojd.quarz.project.monitor.job.service.IJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 调度任务信息操作处理
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/monitor/job")
public class JobController extends BaseController {
    private String prefix = "monitor/job";

    @Autowired
    private IJobService jobService;

    @GetMapping()
    public String job() {
        return prefix + "/job";
    }

    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Job job) {
        startPage();
        List<Job> list = jobService.selectJobList(job);
        return getDataTable(list);
    }

    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Job job) {
        List<Job> list = jobService.selectJobList(job);
        ExcelUtil<Job> util = new ExcelUtil<Job>(Job.class);
        for (long i = 0; i < 1000000; i++) {
            Job job1 = new Job();
            job1.setJobId(i);
            job1.setStatus(0 + "");
            job1.setCronExpression(i + "");
            job1.setJobGroup(i + "");
            job1.setJobName(i + "");
            job1.setMethodName(i + "");
            job1.setMethodParams(i + "");
            job1.setMisfirePolicy(i + "");
            list.add(job1);
        }


        return util.exportExcel(list, "job");
    }

    @GetMapping("/test")
    public void test(HttpServletResponse response) throws IOException {
        TimeInterval timer = DateUtil.timer();
       // List<TestBean> rows = new ArrayList<>(1000000);
        List<List<?>> rows = new ArrayList<>(1000000);
        for (long i = 0; i < 1000000; i++) {
//            TestBean bean1 = new TestBean();
//            bean1.setName("lr"+i);
//            bean1.setAge(12);
//            bean1.setPass(true);
//            bean1.setScore(i);
//            bean1.setExamDate(DateUtil.date());
            List<?> row1 = CollUtil.newArrayList("aa"+i, "bb"+i, "cc", "dd", DateUtil.date());
            rows.add(row1);
        }


       // ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(true);
        ExcelWriter writer= cn.hutool.poi.excel.ExcelUtil.getBigWriter();
        ExcelWriter writer1= writer.setCurrentRow(0);
        Map<String, Object> row1 = new LinkedHashMap<>();
        row1.put("aa名称", "张三");
        row1.put("bb年龄", 23);
        row1.put("cc成绩", 88.32);
        row1.put("dd是否合格", true);
        row1.put("考试日期", DateUtil.date());
        ArrayList<Map<String, Object>> rowshe = CollUtil.newArrayList(row1);
        writer1.write(rowshe);
//        writer.addHeaderAlias("name", "姓名");
//        writer.addHeaderAlias("age", "年龄");
//        writer.addHeaderAlias("score", "分数");
//        writer.addHeaderAlias("isPass", "是否通过");
//        writer.addHeaderAlias("examDate", "考试时间");

// 合并单元格后的标题行，使用默认标题样式
      //  writer.merge(4, "一班成绩单");
// 一次性写出内容，使用默认样式

        writer.write(rows);
        writer.setColumnWidth(4,200);
//        //1. 设置单元格背景色
//// 定义单元格背景色
//       StyleSet style = writer.getStyleSet();
//       style.getHeadCellStyle()
//// 第二个参数表示是否也设置头部单元格背景
//        style.setBackgroundColor(IndexedColors.RED, false);
//       // 2. 自定义字体
//
////设置内容字体
//        Font font = writer.createFont();
//        font.setBold(true);
//        font.setColor(Font.COLOR_RED);
//        font.setItalic(true);
////第二个参数表示是否忽略头部样式
//        writer.getStyleSet().setFont(font, true);
//



        System.out.println("花费毫秒数:" + timer.interval());//花费毫秒数
        System.out.println(timer.intervalRestart());//返回花费时间，并重置开始时间
        System.out.println(timer.intervalMinute());//花费分钟数

        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
//test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=test.xls");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out);
// 关闭writer，释放内存
        writer.close();
    }


    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            jobService.deleteJobByIds(ids);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    @GetMapping("/detail/{jobId}")
    public String detail(@PathVariable("jobId") Long jobId, ModelMap mmap) {
        mmap.put("name", "job");
        mmap.put("job", jobService.selectJobById(jobId));
        return prefix + "/detail";
    }

    /**
     * 任务调度状态修改
     */
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(Job job) {
        return toAjax(jobService.changeStatus(job));
    }

    /**
     * 任务调度立即执行一次
     */
    @PostMapping("/run")
    @ResponseBody
    public AjaxResult run(Job job) {
        return toAjax(jobService.run(job));
    }

    /**
     * 新增调度
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存调度
     */
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Job job) {
        return toAjax(jobService.insertJobCron(job));
    }

    /**
     * 修改调度
     */
    @GetMapping("/edit/{jobId}")
    public String edit(@PathVariable("jobId") Long jobId, ModelMap mmap) {
        mmap.put("job", jobService.selectJobById(jobId));
        return prefix + "/edit";
    }

    /**
     * 修改保存调度
     */
    //@Log(title = "定时任务", businessType = BusinessType.UPDATE)
    //@RequiresPermissions("monitor:job:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Job job) {
        return toAjax(jobService.updateJobCron(job));
    }

    /**
     * 校验cron表达式是否有效
     */
    @PostMapping("/checkCronExpressionIsValid")
    @ResponseBody
    public boolean checkCronExpressionIsValid(Job job) {
        return jobService.checkCronExpressionIsValid(job.getCronExpression());
    }
}
